//
//  WCTService.m
//  WeChatTool
//
//  Created by TerryChe on 2016/12/2.
//  Copyright © 2016年 TerryChe. All rights reserved.
//

#import "WCTMainService.h"
#import "WCTWCDBContactService.h"
#import "WCTMMService.h"
#import "WCTFriend.h"
#import "WCTConfig.h"
#import "FMDB.h"

@interface WCTMainService()

@property (nonatomic, strong) NSString* path;

@property (nonatomic, strong) WCTFriend* me;

@property (nonatomic, assign) BOOL sendFriend;
@property (nonatomic, assign) BOOL sendChat;

@property (nonatomic, assign) BOOL isFirst;

@end

@implementation WCTMainService

-(NSString *)handleWeChatDBBy:(NSString *)path isFirst:(BOOL)isFirst{
    self.sendFriend = false;
    self.sendChat = false;
    self.isFirst = isFirst;
    
    self.me = nil;
    
    log(@"处理 我 的数据");
    NSString *meFilePath = [self handleMeData:path];
    
    if (self.me == nil || meFilePath == nil) {
        return @"";
    }
    log(@"微信号：%@", [self.me getWeChatNo]);
    
    log(@"授权查询以及心跳包");
    [self handleAuthorize];
    log(@"friend:%d chat:%d", self.sendFriend, self.sendChat);
    
    log(@"path:%@", self.path);
    
    if (self.sendFriend) {
        log(@"处理 Friend 数据");
        @try {
            WCTWCDBContactService *contact = [[WCTWCDBContactService alloc]initWith:self.path AndME:self.me AndFilePath:meFilePath];
            [contact handleFriendData];
        }
        @catch (NSException *exception) {
            log(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
        }
    }
        //上传标签
//        [contact handleLabel];
        
    if (self.sendChat) {
        log(@"处理 MM 数据");
        @try {
            WCTMMService *mm = [[WCTMMService alloc]initWith:self.path AndME:self.me AndFilePath:meFilePath];
            [mm handleChatData];
        }
        @catch (NSException *exception) {
            log(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
        }
    }
    
    return _me.wenober;
}

//处理当前帐号数据
-(NSString *)handleMeData:(NSString *)wechatDataPath{
    //获取当前登陆的微信号
    NSString* localInfoPath = [wechatDataPath stringByAppendingPathComponent:str_localInfo];
    if (![[NSFileManager defaultManager] fileExistsAtPath:localInfoPath]) {
        log(@"没找到LocalInfo：%@", localInfoPath);
        return nil;
    }
    
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithContentsOfFile:localInfoPath];
    if (data == nil) {
        return nil;
    }
    NSMutableArray* arrObj = [data objectForKey:@"$objects"];
    if (arrObj == nil || arrObj.count < 2) {
        return nil;
    }
    //当前登陆的微信号
    NSString *wenober = [arrObj[2] isKindOfClass:[NSString class]] ? arrObj[2] : @"";
    if ([wenober isEqualToString:@""]) {
        log(@"微信没登陆");
        return nil;
    }
    log(@"wenober:%@", wenober)
    
    //昵称
    //NSString *name = arrObj.count > 4 && [arrObj[4] isKindOfClass:[NSString class]] ? arrObj[4] : @"";
    
    //转换成MD5
    NSString *md5 = [[WCTConfig sharedInstance] md5:wenober];
    
    //转到对应的MD5文件夹
    self.path = [wechatDataPath stringByAppendingPathComponent:md5];
    
    //获取微信号信息
    NSString* mmsettingPath = [self.path stringByAppendingPathComponent:str_mmsetting];
    if (![[NSFileManager defaultManager] fileExistsAtPath:mmsettingPath]) {
        log(@"没找到mmsetting：%@", mmsettingPath);
        return nil;
    }
    data = [NSMutableDictionary dictionaryWithContentsOfFile:mmsettingPath];
    if (data == nil) {
        return nil;
    }
    arrObj = [data objectForKey:@"$objects"];
    
//    if ([name isEqualToString:@""]) {
//        name = arrObj.count > 3 && [arrObj[3] isKindOfClass:[NSString class]] ? arrObj[3] : @"";
//    }
    NSString *name = arrObj.count > 3 && [arrObj[3] isKindOfClass:[NSString class]] ? arrObj[3] : @"";
    log(@"nickName:%@", name)
    
    //微信号
    NSString *uwenober = @"";
    //头像
    NSString *photo = @"";
    
    for (int i = 0; i < arrObj.count; i++) {
        if ([uwenober isEqualToString:@""] && [arrObj[i] isKindOfClass:[NSString class]] && [arrObj[i] isEqualToString:@"0"]) {
            do {
                i++;
                uwenober = arrObj[i];
            } while ([uwenober isEqualToString:@""] && i < arrObj.count);
        }
        else if ([arrObj[i] isKindOfClass:[NSString class]] && [arrObj[i] hasPrefix:@"http://wx.qlogo.cn/mmhead/ver_1/"] && [arrObj[i] hasSuffix:@"/132"] ) {
            photo = arrObj[i];
        }
    }
    
    self.me = [WCTFriend WCTFriendByWenober:wenober Name:name Photo:photo Remark:@"" Type:0 Uwenober:uwenober Label:@""];
    
    NSString *filePath = [str_wct_dir stringByAppendingPathComponent:[self.me getWeChatNo]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //创建文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //写入user.plist
    data = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
    [data setObject:[self.me getWeChatNo] forKey:wechatDataPath];
    [data writeToFile:[str_wct_dir stringByAppendingPathComponent:str_wct_user] atomically:YES];
    
    //复制
    [[NSFileManager defaultManager] copyItemAtPath:localInfoPath toPath:[filePath stringByAppendingPathComponent:str_wct_localInfo] error:nil];
    
    [[NSFileManager defaultManager] copyItemAtPath:mmsettingPath toPath:[filePath stringByAppendingPathComponent:str_wct_mmsetting] error:nil];
    
    return filePath;
}

-(void)handleAuthorize{
    //检查是否第一次启动
    NSString *first = @"";
    if (_isFirst) {
        first = [NSString stringWithFormat:@"&originalId=%@", self.me.wenober];
    }
    
    NSString* url = [NSString stringWithFormat:@"%@/api/weichart?format=json&access_token=%@&wenober=%@&nickname=%@%@", [WCTConfig sharedInstance].address, [WCTConfig sharedInstance].token, self.me.uwenober, self.me.name, first];

    OPHRequest* request = [OPHRequest jsonReqeust:[url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] type:OPH_HTTP_GET];
    OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
    
    if ([response isRequestOk]) {
        OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
        
        if ([jsonResult isResultSuccess]) {
            self.sendFriend = [jsonResult.result[@"ad_wechat_friends"] boolValue];
            self.sendChat = [jsonResult.result[@"ad_wechat_chat"] boolValue];
        }
    }
}

@end
